import { defineStore } from "pinia";
import { ref } from 'vue'
import { loginAPI } from '@/apis/user'
import { useCartStore } from "./cart";
import { mergeCartAPI,findNewCartListAPI } from "@/apis/cart";
export const useUserStore = defineStore('user', () => {
    const cartStore = useCartStore()
    const userInfo = ref({})

    const getUserInfo = async ({ account, password }) => {
        const { data: res } = await loginAPI({ account, password })
        userInfo.value = res.result
        //合并购物车操作
        const data = cartStore.cartList.map(item => {
            return {
                skuId:item.skuId,
                selected:item.selected,
                count:item.count
            }
        })
        await mergeCartAPI(data) 
        const { data: res1 } = await findNewCartListAPI()       
        cartStore.cartList = res1.result
    }
    //退出登录时，清空用户数据（购物车）
    const clearUserInfo = () => {
        userInfo.value = {}
        // 清空购物车
        cartStore.clearCart()
    }
    return {
        userInfo,
        getUserInfo,
        clearUserInfo
    }
},
    {
        persist: true,
    }
)